const express = require('express')
const router = express.Router()
const adminService = require('services/admin')
const passport = require('../../passport')

const assureAdmin = (req, res, next) => {
  if (req.user.role !== '管理员') {
    return res.status(403).send({ message: '没有权限' })
  }
  next()
}

router.get('/', async (req, res) => {
  res.json(await adminService.findAll())
})

// 修改自己密码
router.put('/password', passport.auth, async (req, res) => {
  try {
    const result = await adminService.modifyPassword(req.user, req.body.originPassword, req.body.newPassword)
    res.json({status: 'sok'})
  } catch (e) {
    res.status(500).send({message: e.message})
  }
})

// 创建、修改他人密码、信息等
router.post('/', passport.auth, assureAdmin, async (req, res, next) => {
  const { username, password, role } = req.body
  if (!username) {
    return res.status(500).send({message: '请填写用户名'})
  }

  if (!password) {
    return res.status(500).send({message: '请填写密码'})
  }

  if (!role) {
    return res.status(500).send({message: '请选择角色'})
  }
  
  try {
    const id = await adminService.createUser({
      username, password, role
    })
    return res.send({ id })
  } catch (e) {
    next(e)
  } 
})

router.put('/:id', passport.auth, assureAdmin, async (req, res) => {
  try {
    const id = req.params.id
    const result = await adminService.updateUser(id, req.body)
    res.json({status: 'ok'})
  } catch (e) {
    res.status(500).send({message: e.message})
  }
})

router.delete('/:id', passport.auth, assureAdmin, async (req, res) => {
  try {
    const id = req.params.id
    const result = await adminService.remove(id)
    res.json({status: 'ok'})
  } catch (e) {
    res.status(500).send({message: e.message})
  }
})

router.put('/:id/password', passport.auth, assureAdmin, async (req, res) => {
  try {
    const id = req.params.id
    const result = await adminService.modifyPassword({ id }, null, req.body.newPassword, true)
    res.json({status: 'ok'})
  } catch (e) {
    res.status(500).send({message: e.message})
  }
})

module.exports = router